package com.example.wyh.intelcheckbash.product_visit;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.MainActivity;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.bug.BugRecordActivity;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by chen on 18/1/17.
 */

public class ScanNewPeoductVisitActivity extends AppCompatActivity {

    TextView mVisitRegion;
    TextView mVisitPeople;
    TextView mVisitTime;
    EditText mVisitRecord;
    Button mSaveAndUploadRecord;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_new_product_activity);
        initActionBar();
        initAllSubViews();
    }

    public void initAllSubViews()
    {
        mVisitRegion = (TextView)findViewById(R.id.visit_region_id);
        mVisitRegion.setText(getIntent().getStringExtra("scanOrigin"));
        mVisitTime = (TextView)findViewById(R.id.visit_time_id);
        mVisitTime.setText(HttpUtil.getCurrentDateTimeString());

        mVisitRecord = (EditText) findViewById(R.id.visit_record_id);
        mVisitPeople = (TextView)findViewById(R.id.visit_people_id);

        //获取用户名
        JSONObject userInfo =  LocalStorage.getObject(ScanNewPeoductVisitActivity.this, "User");
        try {
            String userName = userInfo.getString("usernamecn");
            mVisitPeople.setText(userName);
            final String yhxtm = userInfo.getString("yhxtm");

            mSaveAndUploadRecord = (Button)findViewById(R.id.save_upload_record_id);
            mSaveAndUploadRecord.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    JSONObject productData = new JSONObject();
                    JSONObject newProduct = new JSONObject();
                    try {
                        newProduct.put("xsqysj",mVisitTime.getText().toString());
                        newProduct.put("xsqy",mVisitRegion.getText().toString());
                        newProduct.put("xsr",yhxtm);
                        newProduct.put("xsjg",mVisitRecord.getText().toString());
                        newProduct.put("pk",java.util.UUID.randomUUID().toString());
                        JSONArray allProducts = new JSONArray();
                        allProducts.put(newProduct);
                        productData.put("data",allProducts);
                    }catch (JSONException e)
                    {

                    }
                    saveProductVisitInLocal(productData);
                    HttpUtil.requestNetForPostProductVisitData(productData,ScanNewPeoductVisitActivity.this,"ScanNewPeoductVisitActivity");
                }
            });
        }
        catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
    public void saveProductVisitInLocal(JSONObject updateProduct)
    {
        JSONObject productInfo = new JSONObject();
        try
        {
            productInfo = updateProduct.getJSONArray("data").getJSONObject(0);
        }catch (JSONException e)
        {

        }
        TaskDbHelper taskDbHelper = new TaskDbHelper(ScanNewPeoductVisitActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("user_id",LocalStorage.getUserXtm(ScanNewPeoductVisitActivity.this));
            cv.put("data",productInfo.toString());
            try {
                cv.put("xsxtm",productInfo.getString("pk"));
                cv.put("date",productInfo.getString("xsqysj"));
            }catch (JSONException e)
            {
            }
            cv.put("isUpload","0");
            db.insert("product_list", null, cv);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        db.close();
    }
    public void uploadProductFailed()
    {
        ScanNewPeoductVisitActivity.this.finish();
    }
    public void uploadProductSuccess(final JSONObject result ,final JSONObject uploadData)
    {
        final Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                try {
                    String status = result.getString("status");
                    TaskDbHelper taskDbHelper = new TaskDbHelper(ScanNewPeoductVisitActivity.this);
                    SQLiteDatabase db = taskDbHelper.getWritableDatabase();

                    if (status.equals("success")){
                        for (int i = 0; i < result.getJSONArray("data").length(); i ++)
                        {
                            JSONObject productInfo = new JSONObject();
                            try
                            {
                                productInfo = uploadData.getJSONArray("data").getJSONObject(i);
                            }catch (JSONException e)
                            {

                            }
                            String xsxtm = result.getJSONArray("data").getJSONObject(i).getString("pk");
                            ContentValues cv = new ContentValues();
                            productInfo.put("isUpload","1");
                            cv.put("data",productInfo.toString());
                            cv.put("isUpload","1");
                            int success = db.update("product_list",cv,"user_id=? and xsxtm=?",new String[]{String.valueOf(LocalStorage.getUserXtm(ScanNewPeoductVisitActivity.this)),
                                    String.valueOf(xsxtm)});
                            Log.e("success",success+"");
                            db.close();
                        }
                    }
//                    String success_string = "成功";
//                    String fall_string = "失败";
//                    if(status.equals("success")){
//                        Toast.makeText(ScanNewPeoductVisitActivity.this, "上传"+success_string, Toast.LENGTH_SHORT).show();
//                    }else{
//                        Toast.makeText(ScanNewPeoductVisitActivity.this, "上传"+fall_string, Toast.LENGTH_SHORT).show();
//                    }
                    Toast.makeText(ScanNewPeoductVisitActivity.this, "上传"+status, Toast.LENGTH_SHORT).show();
                }catch (JSONException e)
                {

                }
                // TODO: 18/1/18 跳转到列表页
                ScanNewPeoductVisitActivity.this.finish();
            }
        });

    }
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(ScanNewPeoductVisitActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("生产巡视");
        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.check_task);
        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ScanNewPeoductVisitActivity.this.finish();
            }
        });
    }
}
